package com.ossfk.net.session;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @ClassName: TcpSessionManager
 * @Description: Tcp连接会话管理器
 * @author Liujiefu
 * @date 2020-03-16 16:20:42
 */
@Slf4j
public class TcpSessionManager {
	private Map<String, TcpSession> sessionMap;

	public TcpSessionManager() {
		this.sessionMap = new ConcurrentHashMap<>();
	}

	/**
	 * 
	 * @Description: 会话是否存在
	 * @param id
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:21:03
	 */
	public boolean containsKey(String id) {
		return sessionMap.containsKey(id);
	}

	/**
	 * 
	 * @Description: 会话是否存在
	 * @param session
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:21:21
	 */
	public boolean containsSession(TcpSession session) {
		return sessionMap.containsValue(session);
	}

	/**
	 * 
	 * @Description: 通过id查找会话
	 * @param id
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:21:43
	 */
	public TcpSession findBySessionId(String id) {
		return sessionMap.get(id);
	}

	/**
	 * 添加会话
	 * @param session
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:23:14
	 */
	public synchronized TcpSession addSession(TcpSession session) {
		log.debug("add session:{}", session.toString());
		return sessionMap.put(session.getId(), session);
	}

	/**
	 * 
	 * @Description: 删除会话
	 * @param id
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:21:59
	 */
	public synchronized TcpSession removeBySessionId(String id) {
		if (id == null)
			return null;
		TcpSession session = sessionMap.remove(id);
		// 标记会话已死
		session.setDead(true);
		log.debug("remove session:{}", session.toString());
		return session;
	}

	/**
	 * 更新会话最后通讯时间
	 * 
	 * @author Liujiefu
	 * @date 2020-03-17 11:10:04
	 */
	public TcpSession updateLastCommunicateTime(String id) {
		TcpSession session = findBySessionId(id);
		updateLastCommunicateTime(session);
		return session;
	}

	/**
	 * 更新会话最后通讯时间
	 * 
	 * @author Liujiefu
	 * @date 2020-03-17 11:10:04
	 */
	public void updateLastCommunicateTime(TcpSession session) {
		if (session != null) {
			session.setLastCommunicateTimeStamp(System.currentTimeMillis());
		}
	}

	/**
	 * 
	 * @Description: 获取所有会话id
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:24:15
	 */
	public Set<String> keySet() {
		return sessionMap.keySet();
	}

	/**
	 * 
	 * @Description: 获取所有会话并生成新的list
	 * @return
	 * @author Liujiefu
	 * @date 2020-03-16 16:24:48
	 */
	public List<TcpSession> toList() {
		return this.sessionMap.entrySet().stream().map(e -> e.getValue()).collect(Collectors.toList());
	}
}
